class PastScoreForm {
    constructor() {
        this.form = document.getElementById('pastScoreForm');
        this.totalScorePreview = document.getElementById('totalScorePreview');
        this.init();
    }

    init() {
        this.addInputStyling();
        this.bindEvents();
        this.updateTotalScore();
    }

    // 为输入框添加自定义样式
    addInputStyling() {
        const inputs = document.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            if (!input.classList.contains('form-control-custom') &&
                !input.classList.contains('btn')) {
                input.classList.add('form-control-custom');
            }
        });
    }

    // 绑定事件监听器
    bindEvents() {
        // 动态绑定所有科目分数输入框
        const scoreInputs = document.querySelectorAll('input[id^="id_"]');
        scoreInputs.forEach(input => {
            const fieldId = input.id;
            // 只绑定科目分数输入框，排除年份和总分输入框
            if (fieldId.includes('_score') &&
                !fieldId.includes('total_score') &&
                !fieldId.includes('exam_year') &&
                input.type !== 'hidden') {
                input.addEventListener('input', () => this.updateTotalScore());
            }
        });

        // 表单提交事件
        if (this.form) {
            this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        }
    }

    // 更新总分预览
    updateTotalScore() {
        let total = 0;

        // 获取所有科目分数输入框（包括隐藏的）
        const scoreInputs = document.querySelectorAll('input[id^="id_"]');
        scoreInputs.forEach(input => {
            const fieldId = input.id;
            // 只累加科目分数，排除年份和总分
            if (fieldId.includes('_score') &&
                !fieldId.includes('total_score') &&
                !fieldId.includes('exam_year')) {
                const value = this.getScoreValue(fieldId);
                total += value;
            }
        });

        console.log('动态计算总分:', total);

        if (this.totalScorePreview) {
            this.totalScorePreview.textContent = total;
        }

        // 自动填充总分输入框
        this.autoFillTotalScore(total);
    }

    // 获取分数值
    getScoreValue(fieldId) {
        const input = document.getElementById(fieldId);
        if (input && input.value !== '' && input.type !== 'hidden') {
            return parseFloat(input.value) || 0;
        }
        return 0;
    }

    // 自动填充总分
    autoFillTotalScore(total) {
        const totalScoreInput = document.getElementById('id_total_score');
        if (totalScoreInput) {
            totalScoreInput.value = total;
        }
    }

    // 处理表单提交
    async handleSubmit(e) {
        e.preventDefault();

        const submitBtn = this.form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        // 显示加载状态
        this.setButtonLoading(submitBtn, true);

        try {
            const response = await this.submitForm();

            // 检查响应类型
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                const data = await response.json();

                if (data.success) {
                    this.showAlert('success', data.message);
                    this.redirectToDetailPage();
                } else {
                    this.showFormErrors(data.errors);
                }
            } else {
                // 如果不是 JSON 响应，可能是传统的表单提交
                // 让表单正常提交
                this.form.submit();
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('danger', '保存失败，请重试');
        } finally {
            this.setButtonLoading(submitBtn, false, originalText);
        }
    }

    // 设置按钮加载状态
    setButtonLoading(button, isLoading, originalText = '') {
        if (isLoading) {
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>保存中...';
        } else {
            button.disabled = false;
            button.innerHTML = originalText;
        }
    }

    // 提交表单数据
    async submitForm() {
        const formData = new FormData(this.form);

        return await fetch(this.form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': this.getCSRFToken()
            }
        });
    }

    // 获取 CSRF token
    getCSRFToken() {
        const csrfInput = document.querySelector('[name=csrfmiddlewaretoken]');
        return csrfInput ? csrfInput.value : '';
    }

    // 显示表单错误
    showFormErrors(errors) {
        // 清除之前的错误
        this.clearFormErrors();

        // 添加新的错误
        if (errors) {
            for (const field in errors) {
                this.addFieldError(field, errors[field]);
            }
        }
    }

    // 清除表单错误
    clearFormErrors() {
        document.querySelectorAll('.is-invalid').forEach(el => {
            el.classList.remove('is-invalid');
        });
        document.querySelectorAll('.invalid-feedback').forEach(el => {
            el.remove();
        });
    }

    // 添加字段错误
    addFieldError(field, errorMessages) {
        const input = document.getElementById(`id_${field}`);
        if (input) {
            input.classList.add('is-invalid');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'invalid-feedback';
            errorDiv.innerHTML = Array.isArray(errorMessages) ? errorMessages.join('<br>') : errorMessages;
            input.parentNode.appendChild(errorDiv);

            // 滚动到第一个错误字段
            if (!this.firstErrorField) {
                this.firstErrorField = input;
                input.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }
    }

    // 显示提示消息
    showAlert(type, message) {
        // 移除现有的提示
        document.querySelectorAll('.alert').forEach(alert => alert.remove());

        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        const container = document.querySelector('.container') || document.querySelector('.score-form-container');
        if (container) {
            container.insertBefore(alertDiv, container.firstChild);

            // 自动消失
            if (type === 'success') {
                setTimeout(() => {
                    if (alertDiv.parentNode) {
                        alertDiv.remove();
                    }
                }, 5000);
            }
        }
    }

    // 跳转到详情页
    redirectToDetailPage() {
        setTimeout(() => {
            // 这里需要从 HTML 中获取 URL，或者使用数据属性
            const backLink = document.querySelector('.btn-back');
            if (backLink && backLink.href) {
                window.location.href = backLink.href;
            }
        }, 1500);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    new PastScoreForm();

    // 调试信息
    console.log('PastScoreForm initialized - 动态科目版本');
    console.log('科目输入框数量:', document.querySelectorAll('input[id*="_score"]').length);
});